package ahblue.cn.tanzi.ui.circle;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.shehuan.nicedialog.BaseNiceDialog;
import com.shehuan.nicedialog.NiceDialog;
import com.shehuan.nicedialog.ViewConvertListener;
import com.shehuan.nicedialog.ViewHolder;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.data.Result;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.jmessage.im.util.DialogCreator;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.ui.base.BaseActivity;
import ahblue.cn.tanzi.view.video.MediaPlayer;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IssueDynamicVideoActivity extends BaseActivity {

    public static final int REQUEST_CODE_MAIN = 10; // 请求码

    @BindView(R.id.et_issue_dynamic)
    EditText mEditTextDynamic;
    @BindView(R.id.imageViewAddVideo)
    ImageView mImageViewAddVideo;
    @BindView(R.id.ic_player)
    MediaPlayer mMediaPlayer;
    @BindView(R.id.tv_issue_tongbu)
    TextView tvIssueTongbu;

    @BindView(R.id.cb_issue_dynamic)
    CheckBox mCheckBoxIsOnlyFriends;

    private Dialog mDialogLoading;

    private LoginResultModel mLoginResultModel;
    private String mVideoFileName;
    private String selectedCircleIds = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_issue_dynamic_video);

        ButterKnife.bind(this);

        initData();
        initView();
    }

    private void initData() {
        mLoginResultModel = LoginResultModel.getUserModel(this, LoginResultModel.class);
    }

    private void initView() {
    }

    @Override
    public void onBackPressed() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_cancel_confrim)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    protected void convertView(ViewHolder viewHolder, BaseNiceDialog dialog) {
                        TextView textViewMessage = viewHolder.getView(R.id.textViewMessage);
                        textViewMessage.setText("是否退出编辑？");

                        viewHolder.setOnClickListener(R.id.textViewConfirm, view -> {
                            mMediaPlayer.pausePlay();
                            setResult(RESULT_CANCELED);
                            IssueDynamicVideoActivity.super.onBackPressed();
                            dialog.dismiss();
                        });
                        viewHolder.setOnClickListener(R.id.textViewCancel, view -> {
                            dialog.dismiss();
                        });
                    }
                })
                .setMargin(50)
                .show(getSupportFragmentManager());
    }

    @OnClick(R.id.imageButtonLeft)
    void onClickImageButtonLeft() {
        onBackPressed();
    }

    @OnClick(R.id.tv_issue_tongbu)
    void onClickTvIssueTongbu(){
        Intent intent = new Intent(this, IssueDynamicChooseMyCircleActivity.class);
        startActivityForResult(intent,REQUEST_CODE_MAIN);
    }

    // 发表
    @OnClick(R.id.textViewRight)
    void onClickTextViewRight() {
        String strDynamic = mEditTextDynamic.getText().toString();
        if (strDynamic.length() == 0) {
            Toast.makeText(this, "内容不能为空", Toast.LENGTH_LONG).show();
            return;
        }

        if (selectedCircleIds == null || "".equals(selectedCircleIds)){
            Toast.makeText(this, "请选择需要同步到的圈子", Toast.LENGTH_LONG).show();
            return;
        }

        mDialogLoading = DialogCreator.createLoadingDialog(this, "正在上传");
        mDialogLoading.show();

        int isFriends = mCheckBoxIsOnlyFriends.isChecked() ? 1 : 0;

        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.addBigShotCircleSendDynamic(mLoginResultModel.token, strDynamic,selectedCircleIds, isFriends,
                null, mVideoFileName, mCallbackAddDynamic);
    }

    @OnClick(R.id.imageViewAddVideo)
    void onClickAddVideo() {
        final Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_MAIN);
    }

    private ApiCallback<Result> mCallbackAddDynamic = new ApiCallback<Result>() {
        @Override
        public void onSuccess(Result data) {
            Toast.makeText(IssueDynamicVideoActivity.this, "发表成功", Toast.LENGTH_LONG).show();
            IssueDynamicVideoActivity.this.setResult(RESULT_OK);
            IssueDynamicVideoActivity.this.finish();

            if (mDialogLoading != null) {
                mDialogLoading.dismiss();
            }
        }

        @Override
        public void onFailed(String errorMsg) {
            if (mDialogLoading != null) {
                mDialogLoading.dismiss();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUEST_CODE_MAIN:
                    // 视频选择结果回调
                    Uri selectedVideo = data.getData();
                    String[] filePathColumn = { MediaStore.Video.Media.DATA };

                    Cursor cursor = getContentResolver().query(selectedVideo ,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    mVideoFileName = cursor.getString(columnIndex);
                    cursor.close();

                    if (mVideoFileName != null && mVideoFileName.length() > 0) {
                        mImageViewAddVideo.setVisibility(View.GONE);
                        mMediaPlayer.setVideoPath(mVideoFileName, this);
                        mMediaPlayer.setVisibility(View.VISIBLE);
                    }

                    break;
            }
        }

        if (requestCode == REQUEST_CODE_MAIN && data != null){
            String ids = data.getStringExtra("selectedCircleIds");
            if (ids != null && !"".equals(ids)){
                selectedCircleIds = ids;
            }

            String selectedCircleNames = data.getStringExtra("selectedCircleNames");
            if (selectedCircleNames != null && !"".equals(selectedCircleNames)){
                selectedCircleNames = selectedCircleNames.substring(1);
                tvIssueTongbu.setText(selectedCircleNames);
            }

        }
    }
}
